package com.weipai.demo.util;

import com.alibaba.fastjson.JSON;
import com.weipai.demo.enums.RetCode;
import com.weipai.demo.model.DUser;
import com.weipai.demo.model.LoansManager;
import com.weipai.demo.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录检查
 */
@Component
public class LoginHandlerInterceptor implements HandlerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(LoginHandlerInterceptor.class);
    public static final String AUTH_TOKEN_HEADER = "Authentication-Token";
    @Autowired
    private UserService userService;

    //目标方法执行之前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String authToken = request.getHeader(AUTH_TOKEN_HEADER);
        String u_t = request.getParameter("u_t");
        Response ret = new Response();

        if ("".equals(u_t) || "2".equals(u_t) || u_t == null) {
            if (authToken != null && !authToken.equals("")) {
                //app端
                boolean isValid = false;
                try {
                    isValid = com.weipai.demo.util.PasswordHelper.validateToken(authToken);
                } catch (Exception e) {
                    logger.error("validate token with error = {}", e);
                }
                if (isValid) {
                    if ("".equals(u_t) || u_t == null) { //前端信贷经理
                        //已登录
                        String username = com.weipai.demo.util.PasswordHelper.getUserName(authToken);
                        LoansManager loansManager = userService.getLoanByLoginName(username);
                        if (loansManager == null) {
                            //返回未登录
                            ret.setCode(RetCode.NOT_LOGIN);
                            response.setCharacterEncoding("utf-8");
                            response.getWriter().append(JSON.toJSONString(ret));
                            return false;
                        } else if (loansManager.getStatus() == 0) {
                            //返回未审核
                            ret.setCode(RetCode.NO_PAY);
                            ret.setMsg("您已提交申请,请耐心等待审核,工作人员会在三个工作日之内联系您!");
                            response.setCharacterEncoding("utf-8");
                            response.getWriter().append(JSON.toJSONString(ret));
                            return false;
                        } else if (loansManager.getIsPay() == "0") {
                            //返回未支付
                            ret.setCode(RetCode.NO_PAY);
                            response.setCharacterEncoding("utf-8");
                            response.getWriter().append(JSON.toJSONString(ret));
                            return false;
                        }
                    } else {

                        //已登录
                        String username = com.weipai.demo.util.PasswordHelper.getUserName(authToken);
                        DUser user = userService.getUserByLoginName(username);
                        if (user == null) {
                            //返回未登录
                            ret.setCode(RetCode.NOT_LOGIN);
                            response.setCharacterEncoding("utf-8");
                            response.getWriter().append(JSON.toJSONString(ret));
                            return false;
                        }

                    }
                    return true;
                } else {
                    //返回未登录
                    response.setCharacterEncoding("utf-8");
                    ret.setCode(RetCode.NOT_LOGIN);
                    response.getWriter().append(JSON.toJSONString(ret));
                    return false;

                }

            } else {
                response.setCharacterEncoding("utf-8");
                ret.setCode(RetCode.NOT_LOGIN);
                response.getWriter().append(JSON.toJSONString(ret));
                return false;
            }
        }
        /*else{
            Subject subject = SecurityUtils.getSubject();
            Session session = subject.getSession();
            user user = (user) session.getAttribute(user.KEY);
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            if (user == null) {
               *//* ret.setCode(RetCode.NOT_LOGIN);
                response.getWriter().append(JSON.toJSONString(ret));*//*
                return true;
            } else {
                return true;
            }
        }*/
        return true;
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {

    }
}
